package com.gss.plugin.oauth2.handler;

import com.alibaba.fastjson.JSONObject;
import com.gss.entity.R;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author DYang
 * @date 2023/8/19
 * 自定义实现登录成功页面跳转
 */
public class CustomAuthSuccessHandler implements AuthenticationSuccessHandler {

    private String url;

    public CustomAuthSuccessHandler() {
    }

    public CustomAuthSuccessHandler(String url) {
        this.url = url;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取用户信息
        User user = (User) authentication.getPrincipal();

        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Content-Type","application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();

        R<User> res = R.ok(user);
        writer.write(JSONObject.toJSONString(res));
        writer.flush();
        writer.close();
    }
}
